/*
 * @Description:
 * @Date: 2023-02-21 17:11:15
 * @LastEditors: czp
 * @LastEditTime: 2023-04-23 10:23:43
 */
import { baseGetShare } from "@/service/modules/base";

export interface IJsSdkConf {
	signature: string;
	appid: string;
	jsapi_ticket: string;
	noncestr: string;
	url: string;
	timestamp: number;
}

export interface IShareData {
	shareTitle: string;
	shareDesc: string;
	shareTimeline: string;
	shareImage: string;
	shareUrl: string;
	jsSdkConf: IJsSdkConf;
}
export const useWxSdk = () => {
	const shareData = ref<IShareData>();

	/**
	 * 获取分享信息
	 */
	const getShare = async () => {
		try {
			const url = location.origin + location.pathname + location.hash;
			const { data } = await baseGetShare({ url });
			shareData.value = data;
		} catch (error) {}
	};

	/**
	 * 初始化sdk
	 */
	const initSdk = () => {
		wx.config({
			beta: true, //调用未公开的接口
			debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
			appId: shareData.value.jsSdkConf.appid, // 必填，公众号的唯一标识
			timestamp: shareData.value.jsSdkConf.timestamp, // 必填，生成签名的时间戳
			nonceStr: shareData.value.jsSdkConf.noncestr, // 必填，生成签名的随机串
			signature: shareData.value.jsSdkConf.signature, // 必填，签名
			// ...shareData.value.jsSdkConf,
			jsApiList: ["updateAppMessageShareData", "updateTimelineShareData", "chooseImage", "scanQRCode", "invoke"] // 必填，需要使用的JS接口列表
		});
	};

	/**
	 * 设置分享
	 */
	const wsShare = () => {
		wx.ready(() => {
			wx.updateAppMessageShareData({
				title: shareData.value.shareTitle, // 分享标题
				desc: shareData.value.shareDesc, // 分享描述
				link: shareData.value.shareUrl, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
				imgUrl: shareData.value.shareImage, // 分享图标
				success: () => {}
			});
			wx.updateTimelineShareData({
				title: shareData.value.shareTimeline, // 分享标题
				link: shareData.value.shareUrl, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
				imgUrl: shareData.value.shareImage, // 分享图标
				success: () => {}
			});
			wx.hideMenuItems({
				menuList: ["menuItem:copyUrl", "menuItem:share:qq", "menuItem:share:QZone"] // 要隐藏的菜单项，只能隐藏“传播类”和“保护类”按钮，所有menu项见附录3
			});
		});
	};

	onMounted(async () => {
		await getShare();
		initSdk();
		wsShare();
	});
};
